<template>

  <div style="width: 100%;">

    <!-- 筛选条件 -->
    <div class="filter-container">
        <el-form :model="filterForm" inline>
            <el-form-item label="组织状态">
                <el-select v-model="filterForm.status" style="width: 200px" placeholder="请选择组织状态" clearable>
                    <el-option label="显示" :value="1" />
                    <el-option label="不显示" :value="2" />
                </el-select>
            </el-form-item>
            
          
            <el-form-item label="组织名称">
                <el-input
                    v-model="filterForm.title"
                    placeholder="请输入组织名称"
                    clearable
                    style="width: 200px"
                />
            </el-form-item>
            
            
            <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>
    </div>


    <div class="menu-management" style="width: 100%;">
      <div class="header">
          <!-- <h2>组织管理</h2> -->
          <el-button type="primary" @click="handleAdd" v-permission="'admin:basic/organization:add'">新增组织</el-button>
      </div>

      <el-table 
          :data="filteredMenuList" 
          row-key="id" 
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          v-loading="loading" style="font-size: 12px;"
      >
      <el-table-column prop="title" label="组织名称" min-width="100"></el-table-column>
      
      <el-table-column prop="truename" label="租户名称" ></el-table-column>

      <el-table-column prop="sort" label="排序" width="80"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
          <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="2"
              @change="handleStatusChange(row)"
          />
          </template>
      </el-table-column>
      <el-table-column prop="curator" label="负责人" width="120"></el-table-column>
      <el-table-column prop="remark" label="备注" width="220"></el-table-column>

      <el-table-column prop="create_at" label="添加时间" width="220"></el-table-column>

      <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)" v-permission="'admin:basic/organization:edit'">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)" v-permission="'admin:basic/organization:del'">删除</el-button>
          </template>
      </el-table-column>
      </el-table>

      <!-- 新增/编辑对话框 -->
      <el-dialog
          :title="dialogTitle"
          v-model="dialogVisible"
          width="700px"
          :before-close="handleClose"
      >
          <el-form
              ref="formRef"
              :model="formData"
              :rules="formRules"
              label-width="100px"
          >

              <el-form-item label="父级节点" prop="pid">
                <el-tree-select
                    @change="handleOrganizationChange"
                    v-model="formData.pid"
                    :data="menuTreeData"
                    check-strictly
                    :render-after-expand="false"
                    placeholder="请选择父级节点"
                    style="width: 100%"
                />
              </el-form-item>

              <el-form-item label="名称" prop="title">
              <el-input
                  v-model="formData.title"
                  placeholder="请输入名称（最多20字）"
                  maxlength="20"
                  show-word-limit
              />
              </el-form-item>

              <el-form-item label="负责人" prop="curator">
                <el-select 
                  v-model="formData.curator"
                  placeholder="请选择负责人"
                  style="width: 100%"
                  clearable
                >
                  <el-option v-for="item in member_list" :label="item.truename" :value="item.id" />
                </el-select>
              </el-form-item>

              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  placeholder="请输入备注信息（最多150字）"
                  maxlength="150"
                  show-word-limit
                  :rows="3"
                />
              </el-form-item>


              <el-form-item label="排序" prop="sort">
                <el-input-number
                    v-model="formData.sort"
                    :min="0"
                    :max="999"
                    controls-position="right"
                />
              </el-form-item>

              <el-form-item label="显示状态" prop="status">
                <el-radio-group v-model="formData.status">
                    <el-radio :label="1">显示</el-radio>
                    <el-radio :label="2">不显示</el-radio>
                </el-radio-group>
              </el-form-item>
          </el-form>

          <template #footer>
              <span class="dialog-footer">
              <el-button @click="handleClose">取消</el-button>
              <el-button type="primary" @click="handleSubmit">确定</el-button>
              </span>
          </template>
      </el-dialog>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed  } from 'vue'
import { menuApi, type MenuItem} from '@/api/Organization'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'


interface FilterForm {
  status: number | null
  title: string
}


// 响应式数据
const menuList = ref<MenuItem[]>([])
const flatMenuList = ref<MenuItem[]>([]) // 新增：扁平组织列表
const loading = ref(false)
const formRef = ref()
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentId = ref<number | null>(null)


// 计算属性 - 构建树形选择器数据
const menuTreeData = computed(() => {
  if (!flatMenuList.value.length) return []
  
  const formatTree = (menus: MenuItem[], parentId: number = 0): any[] => {
    return menus
      .filter(menu => menu.pid === parentId)
      .map(menu => ({
        value: menu.id,
        label: `${menu.title}`,
        disabled: isEdit.value && currentId.value === menu.id, // 编辑时不能选择自己作为父级
        children: formatTree(menus, menu.id)
      }))
  }
  
  // 添加一个虚拟的根节点来代表"顶级"
  // const rootOption = {
  //   value: 0,
  //   label: '顶级',
  //   disabled: false, // 不应该禁用顶级选项
  //   children: formatTree(flatMenuList.value, 0)
  // }
  
  // return [rootOption]

  //return formatTree(flatMenuList.value, 0)

  // 只在编辑时显示"顶级"选项
  if (isEdit.value) {
    // 添加一个虚拟的根节点来代表"顶级"
    const rootOption = {
      value: 0,
      label: '顶级',
      disabled: false,
      children: formatTree(flatMenuList.value, 0)
    }
    return [rootOption]
  } else {
    // 添加时直接显示组织列表
    return formatTree(flatMenuList.value, 0)
  }


})


// 加载扁平组织列表（用于树形选择器）
const loadFlatMenuList = async () => {
  try {
    const response = await menuApi.getMenuFlatList(formData.system_user_id)
    if (response.code === 200) {
      flatMenuList.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取组织列表失败')
  }
}


// 筛选表单
const filterForm = reactive<FilterForm>({
  status: null,
  title: '',
})

// 表单数据
const formData = reactive({
  system_user_id:'',
  title: '',
  pid: null as number | null | string,
  remark: '',
  curator: '',
  sort: 0,
  status: 1 as 1 | 2
})


// 表单验证规则
const formRules: any = {
  title: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    { max: 20, message: '组织名称不能超过20个字符', trigger: 'blur' }
  ],
  pid: [
    { required: true, message: '请选择父级节点', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择显示状态', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ],
  remark: [
    { max: 150, message: '备注不能超过150个字符', trigger: 'blur' }
  ]
}
// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑组织' : '新增组织')


const filteredMenuList = computed(() => {
  // 如果没有任何筛选条件，则返回原始组织列表
  const hasFilter = filterForm.status !== null || 
                   filterForm.title.trim() !== '' 
                   
  if (!hasFilter) {
    return menuList.value;
  }
  
  // 递归过滤组织及其子组织
  const filterMenus = (menus: MenuItem[]): MenuItem[] => {
    return menus.filter(menu => {
      // 检查当前组织是否符合过滤条件
      const matchesStatus = !filterForm.status || menu.status === filterForm.status;
      const matchesTitle = !filterForm.title || menu.title.toLowerCase().includes(filterForm.title.toLowerCase());
      
      const matchesAll = matchesStatus && matchesTitle;
      
      // 如果有子组织，递归过滤子组织
      if (menu.children && menu.children.length > 0) {
        const filteredChildren = filterMenus(menu.children);
        // 如果子组织中有符合条件的，或者当前组织符合条件，则保留该组织
        return matchesAll || filteredChildren.length > 0 ? 
          {...menu, children: filteredChildren} : 
          null;
      }
      
      // 叶子节点只需检查自身是否符合条件
      return matchesAll;
    }).filter((menu): menu is MenuItem => menu !== null); // 类型守卫过滤掉null值
  };
  
  return filterMenus(menuList.value);
});

// 方法
const handleAdd = async () => {
  isEdit.value = false
  currentId.value = null


  Object.assign(formData, {
    system_user_id:'',
    title: '',
    pid: null,
    remark: '',
    curator: '',
    sort: 0,
    status: 1
  })

  await loadFlatMenuList()

  dialogVisible.value = true
}

const member_list = ref()
const handleOrganizationChange = (value: string) => {
  formData.pid = value
  menuApi.getMemberList(Number(value)).then(res => { 
    formData.curator = ''
    member_list.value = res.data
  })
}

const handleEdit = async (row: any) => {
  isEdit.value = true
  currentId.value = row.id

  menuApi.getMemberList(Number(row.id)).then(res => { 
    formData.curator = ''
    member_list.value = res.data
  })


  Object.assign(formData, {
    system_user_id: row.system_user_id,
    title: row.title,
    pid: row.pid !== undefined ? Number(row.pid) : null, // 确保正确处理 undefined
    remark: row.remark,
    curator: row.curator,
    sort: row.sort,
    status: row.status
  })

  await loadFlatMenuList()

  dialogVisible.value = true
}


// 获取组织列表
const loadMenuList = async (json?:any) => {
  try {
    loading.value = true
    const response = await menuApi.getMenuList(json)
    if (response.code === 200) {
      menuList.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    ElMessage.error('获取组织列表失败')
  } finally {
    loading.value = false
  }
}


const handleSearch = () => {
  loading.value = true
  
  let json = { ...filterForm }
  // 模拟搜索延迟
  setTimeout(() => {
    loading.value = false
    loadMenuList(json)
    ElMessage.success('查询完成')
  }, 500)
}

const handleReset = () => {
  Object.assign(filterForm, {
    status: null,
    cache_status: null,
    title: '',
    business: ''
  })
  ElMessage.success('已重置筛选条件')
}

const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.clearValidate()
}

// 新增组织
const handleSubmit = async () => {
  if (!formRef.value) return

  const valid = await formRef.value.validate()
  if (!valid) return

  try {
    if (isEdit.value && currentId.value) {
      // 编辑组织
      const response = await menuApi.updateMenu(currentId.value, formData)
      if (response.code === 200) {
        ElMessage.success('编辑成功')
        loadMenuList() // 重新加载列表
        dialogVisible.value = false
      } else {
        ElMessage.error(response.message)
      }
    } else {
      // 新增组织
      const response = await menuApi.createMenu(formData)
      if (response.code === 200) {
        ElMessage.success('新增成功')
        loadMenuList() // 重新加载列表
        dialogVisible.value = false
      } else {
        ElMessage.error(response.message)
      }
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除组织
const handleDelete = async (row: MenuItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除组织 "${row.title}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await menuApi.deleteMenu(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadMenuList() // 重新加载列表
    } else {
      ElMessage.error(response.message)
    }
  } catch {
    // 用户取消删除
  }
}

// 状态切换
const handleStatusChange = async (row: MenuItem) => {
  try {
    const response = await menuApi.updateMenuStatus(row.id, row.status)
    if (response.code === 200) {
      ElMessage.success(`状态已${row.status === 1 ? '启用' : '禁用'}`)
    } else {
      ElMessage.error(response.message)
      // 恢复原状态
      row.status = row.status === 1 ? 2 : 1
    }
  } catch (error) {
    ElMessage.error('状态更新失败')
    // 恢复原状态
    row.status = row.status === 1 ? 2 : 1
  }
}

// 初始化加载
onMounted(() => {
  loadMenuList()
  loadFlatMenuList()
})
</script>

<style scoped>
.menu-management {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 0px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.menu-icon {
  width: 24px;
  height: 24px;
  object-fit: contain;
}

.icon-upload {
  display: flex;
  align-items: center;
  gap: 12px;
}

.preview-icon {
  width: 40px;
  height: 40px;
  object-fit: contain;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 4px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 16px;
  margin-bottom: 0;
}

.on{
    color: #1079E6;
    font-weight: bold;
}
</style>